// src/com/estore/network/EStoreServer.java
package estore.network;

import estore.service.ProductService;
import estore.model.Product;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/**
 * EStore 服务器类，负责监听客户端连接并处理请求
 */
public class EStoreServer {

    private static final int PORT = 8888;
    private final ProductService productService = new ProductService();

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.start();
    }

    /**
     * 启动服务器，监听指定端口
     */
    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器启动成功，正在监听端口 " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getRemoteSocketAddress());

                handleClient(clientSocket);
            }
        } catch (IOException e) {
            System.err.println("服务器运行异常：" + e.getMessage());
        }
    }

    /**
     * 处理单个客户端请求
     *
     * @param clientSocket 客户端 socket 连接
     */
    private void handleClient(Socket clientSocket) {
        try (
                ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
                ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())
        ) {
            // 1. 读取客户端发送的请求字符串
            String request = (String) input.readObject();

            // 2. 根据请求类型调用对应方法获取数据
            List<Product> result = null;
            switch (request) {
                case "GET_ALL_PRODUCTS":
                    result = productService.getAllProducts();
                    break;
                default:
                    System.err.println("未知请求：" + request);
                    output.writeObject("ERROR: 未知请求");
                    return;
            }

            // 3. 将结果写回客户端
            output.writeObject(result);
            output.flush(); // 确保数据被发送

            System.out.println("已向客户端发送数据：" + result.size() + " 个商品");

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求时发生错误：" + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败：" + e.getMessage());
            }
        }
    }
}
